package com.centerm.structure.service.impl;


import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.centerm.common.exception.MyRuntimeException;
import com.centerm.structure.dao.UserRoleDao;
import com.centerm.structure.domain.UserRole;
import com.centerm.structure.dto.RoleInfo;
import com.centerm.structure.dto.UserRoleInfo;
import com.centerm.structure.service.UserRoleService;

/**
 * 
* @ClassName: UserServiceImpl
* @Description: 用户角色关系实现类
* @author czy
* @date 2017年8月16日
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleDao userRoleDao;

	@Override
	@Transactional
	public Integer update(UserRoleInfo userRoleInfo) {
		Integer result = 0;
		String ids = userRoleInfo.getRoleIds();
		Integer userId = userRoleInfo.getUserId();
		if(StringUtils.isBlank(ids)){
			throw new MyRuntimeException("权限id集合ids can not be null!");
		}
		//先删除旧记录
		userRoleDao.deleteByUserId(userId);
		//再新增新记录
		UserRole userRole = null;
		for(String id : ids.split(",")){
			userRole = new UserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(Integer.valueOf(id));
			userRoleDao.insert(userRole);
			result++;
		}
		return result;
	}

	@Override
	public List<RoleInfo> listByParam(UserRoleInfo userRoleInfo) {
		List<RoleInfo> roleInfoList = userRoleDao.listByUserId(userRoleInfo);
		return roleInfoList;
	}

}
